package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.constant.RedisConst;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Date;
import java.util.Map;

/**
 * @author mengwei
 * @date 2019/8/19
 * @desc
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    JedisPool jedisPool;

    @Reference
    MemberService memberService;

    @RequestMapping("/check")
    public Result login(@RequestBody Map<String,String> map){
        try {
            //获取手机号
            String telephone = map.get("telephone");
            //获取redis中存储的验证码
            String validateCodeRedis = jedisPool.getResource().get(RedisConst.SENDTYPE_LOGIN + "-" + telephone);
            //获取传过来的验证码
            String validateCodeUser = map.get("validateCode");
            if (!(validateCodeRedis != null && validateCodeRedis.equals(validateCodeUser))){
                return new Result(false, MessageConst.VALIDATECODE_ERROR);
            }
            //判断是否是会员
            Member member = memberService.findByTelephone(telephone);
            if (member == null){
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.addMember(member);
            }
            return new Result(true,MessageConst.LOGIN_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.TELEPHONE_VALIDATECODE_NOTNULL);
        }
    }
}
